#include<d3d9.h>
#include<d3dx9.h>

#include"AppState.h"
#include"AppState_Splash.h"

#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")

#define	WINDOW_CLASS	L"UGPDX"
#define	WINDOW_NAME		L"learn_d3d_basic"
#define	WINDOW_SIZE_HEIGHT	480
#define	WINDOW_SIZE_WIDTH	640


bool InitializeD3D( HWND hwnd, bool bwindowed);
bool Setup();
void Cleanup();
void RenderScene();


AppState	*g_pAppState = 0;

LPDIRECT3D9				g_pd3d = 0;
LPDIRECT3DDEVICE9		g_pDevice = 0;

LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch(msg)
	{
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
		break;

	case WM_KEYUP:
		if(wParam == VK_ESCAPE) PostQuitMessage(0);
		break;
	}

	return DefWindowProc(hWnd, msg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE prevhInst, LPSTR cmdLine, int show)
{
	// Register the window class
	WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
		GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
		WINDOW_CLASS, NULL };
	RegisterClassEx(&wc);

	// Create the application's window
	HWND hWnd = CreateWindow(WINDOW_CLASS, WINDOW_NAME, WS_OVERLAPPEDWINDOW,
		100, 100, 640, 480, GetDesktopWindow(), NULL,
		wc.hInstance, NULL);



	if( InitializeD3D( hWnd, true))
	{
		Setup();

		// Show the window
		ShowWindow(hWnd, SW_SHOWDEFAULT);
		UpdateWindow(hWnd);

		// Enter the message loop
		MSG msg;
		ZeroMemory(&msg, sizeof(msg));

		while(msg.message != WM_QUIT)
		{
			if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
			else
				RenderScene();
		}
	}

	Cleanup();

	return 0;
}


bool InitializeD3D( HWND hwnd, bool bwindowed)
{
	g_pd3d = Direct3DCreate9( D3D_SDK_VERSION);
	if ( g_pd3d == 0 )
		return false;

	D3DDISPLAYMODE	displayMode;
	g_pd3d->GetAdapterDisplayMode( D3DADAPTER_DEFAULT,&displayMode);
	
	D3DPRESENT_PARAMETERS	d3dpp;
	ZeroMemory(&d3dpp,sizeof(d3dpp));
	
	d3dpp.Windowed = bwindowed;
	if( !bwindowed)
	{
		d3dpp.BackBufferHeight = WINDOW_SIZE_HEIGHT;
		d3dpp.BackBufferWidth = WINDOW_SIZE_WIDTH;
	}

	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = displayMode.Format;

	if( FAILED( g_pd3d->CreateDevice( D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwnd,D3DCREATE_HARDWARE_VERTEXPROCESSING,&d3dpp,&g_pDevice )))
	{
		return false;
	}

	return true;
}

bool Setup()
{
	g_pAppState = new AppState_Splash();
	return true;
}

void RenderScene()
{
	g_pDevice->Clear( 0,0,D3DCLEAR_TARGET,D3DCOLOR_XRGB( 0,0,255),1.0f,0);

	g_pDevice->BeginScene();

	g_pDevice->EndScene();
	g_pDevice->Present( 0,0,0,0 );
}


void Cleanup()
{
	if( g_pDevice )
	{
		g_pDevice->Release();
		g_pDevice = 0;
	}

	if( g_pd3d )
	{
		g_pd3d->Release();
		g_pd3d = 0;
	}

	if( g_pAppState )
	{
		delete g_pAppState;
		g_pAppState = 0;
	}	
}

